package com.itheima.bakery.demos.web.controller;

import com.itheima.bakery.demos.web.Utility.CookieUtils;
import com.itheima.bakery.demos.web.model.Order;
import com.itheima.bakery.demos.web.model.User;
import com.itheima.bakery.demos.web.service.UserService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import com.itheima.bakery.demos.web.model.ShippingAddress;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import com.itheima.bakery.demos.web.model.*;
@CrossOrigin(origins="*")
@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    private static final String SECRET_KEY = "ccb0d5cf-ac74-4cad-8ba0-5f95e80b38cb";
    @Autowired
    public UserController(UserService userService, PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }

    @GetMapping
    public List<User> listUsers() {
        return userService.findAllUsers();
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Integer id) {
        return userService.findUserById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.saveUser(user);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Integer id) {
        userService.deleteUser(id);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/login")
    public ResponseEntity<?> loginUser(@RequestBody LoginRequest loginRequest, HttpServletResponse response) {
        String inputEmail = loginRequest.getEmail();
        String inputPassword = loginRequest.getPassword();
        Optional<User> userOptional = userService.findUserByEmail(inputEmail);

        if (userOptional.isEmpty()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Email not found");
        }

        User user = userOptional.get();
        boolean isPasswordMatch = inputPassword.equals(user.getPassword()); // 明文比较密码

        if (!isPasswordMatch) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Password incorrect");
        }

        // 生成JWT令牌，包含用户角色
        String token = generateToken(user);

        // 设置用户ID的Cookie
        Cookie userIdCookie = new Cookie("user_id", String.valueOf(user.getUserID()));
        userIdCookie.setHttpOnly(true);
        userIdCookie.setPath("/");
        userIdCookie.setMaxAge(60 * 60 * 24 * 7); // 7天有效期
        response.addCookie(userIdCookie);

        // 设置认证令牌的Cookie
        Cookie tokenCookie = new Cookie("auth_token", token);
        tokenCookie.setHttpOnly(true);
        tokenCookie.setPath("/");
        tokenCookie.setMaxAge(60 * 60 * 24 * 7); // 7天有效期
        response.addCookie(tokenCookie);

        // 创建登录成功的响应对象
        LoginResponse loginResponse = new LoginResponse(user.getUserID(), token);
        return ResponseEntity.ok(loginResponse);
    }

    private String generateToken(User user) {
        return Jwts.builder()
                .setId(String.valueOf(user.getUserID()))
                .setSubject(user.getEmail())
                .claim("role", user.getRole()) // 包含用户角色
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 604800000)) // 7天有效期
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                .compact();
    }


    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Integer id, @RequestBody User userRequest) {
        return userService.findUserById(id)
                .map(user -> {
                    user.setName(userRequest.getName());
                    user.setEmail(userRequest.getEmail());
                   user.setRegistrationDate(userRequest.getRegistrationDate());
                   user.setShippingAddresses(userRequest.getShippingAddresses());
                   user.setPassword(userRequest.getPassword());
                    return ResponseEntity.ok(userService.saveUser(user));
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/my-endpoint")
    public String myEndpoint(HttpServletRequest request) {
        return CookieUtils.getUserIdCookie(request)
                .map(userId -> "User ID: " + userId)
                .orElse("No user ID cookie found");
    }

    @GetMapping("/get-user-info")
    public ResponseEntity<User> getUserInfo(@RequestParam Integer userId) {
        User user = userService.findUserById(userId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"));
        return ResponseEntity.ok(user);
    }

    @GetMapping("/get-orders")
    public ResponseEntity<List<Order>> getOrders(@RequestParam Integer userId) {
        List<Order> orders = userService.findOrdersByUserId(userId);
        return ResponseEntity.ok(orders);
    }
    @PostMapping("/logout")
    public ResponseEntity<?> logoutUser(HttpServletRequest request, HttpServletResponse response) {
        // 清除服务器端的会话信息
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }

        // 清除Cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("JSESSIONID".equals(cookie.getName()) || "auth_token".equals(cookie.getName()) || "user_id".equals(cookie.getName())) {
                    cookie.setValue("");
                    cookie.setPath("/");
                    cookie.setMaxAge(0); // 设置立即过期
                    response.addCookie(cookie);
                }
            }
        }

        // 设置响应头以防止缓存
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");

        return ResponseEntity.ok().body("logout_success"); // 确保返回的字符串与前端期望的一致
    }
    @GetMapping("/shipping-addresses/{userId}")
    public ResponseEntity<List<ShippingAddress>> getUserShippingAddresses(@PathVariable Integer userId) {
        return userService.findUserById(userId)
                .map(user -> ResponseEntity.ok((List<ShippingAddress>) user.getShippingAddresses()))
                .orElse(ResponseEntity.notFound().build());
    }
    @PutMapping("/shipping-addresses/{userId}")
    public ResponseEntity<ShippingAddress> updateUserShippingAddress(@PathVariable Integer userId, @RequestBody ShippingAddress shippingAddress) {
        return userService.findUserById(userId)
                .map(user -> {
                    user.getShippingAddresses().add(shippingAddress); // 假设您允许添加多个地址
                    userService.saveUser(user);
                    return ResponseEntity.ok(shippingAddress);
                })
                .orElse(ResponseEntity.notFound().build());
    }
    @PostMapping("/admin/login")
    public ResponseEntity<?> adminLogin(@RequestBody LoginRequest loginRequest, HttpServletResponse response) {
        String inputEmail = loginRequest.getEmail();
        String inputPassword = loginRequest.getPassword();
        Optional<User> userOptional = userService.findUserByEmail(inputEmail);

        if (userOptional.isEmpty()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Email not found");
        }

        User user = userOptional.get();
        boolean isPasswordMatch = inputPassword.equals(user.getPassword()); // 明文比较密码

        if (!isPasswordMatch) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Password incorrect");
        }

        // 检查用户是否是管理员
        if (!user.getRole().equals("admin")) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Access denied: User is not an administrator");
        }

        // 生成JWT令牌，包含用户角色
        String token = generateToken(user);

        // 设置用户ID的Cookie
        Cookie userIdCookie = new Cookie("user_id", String.valueOf(user.getUserID()));
        userIdCookie.setHttpOnly(true);
        userIdCookie.setPath("/");
        userIdCookie.setMaxAge(60 * 60 * 24 * 7); // 7天有效期
        response.addCookie(userIdCookie);

        // 设置认证令牌的Cookie
        Cookie tokenCookie = new Cookie("auth_token", token);
        tokenCookie.setHttpOnly(true);
        tokenCookie.setPath("/");
        tokenCookie.setMaxAge(60 * 60 * 24 * 7); // 7天有效期
        response.addCookie(tokenCookie);

        // 创建登录成功的响应对象
        LoginResponse loginResponse = new LoginResponse(user.getUserID(), token);
        return ResponseEntity.ok(loginResponse);
    }




}